package com.cykj.interceptoer;

import com.alibaba.fastjson2.JSON;
import com.cykj.dto.ResponseDto;
import com.cykj.util.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @BelongsProject: Psychology
 * @BelongsPackage: com.cykj.interceptoer
 * @Author: 小林
 * @CreateTime: 2025-02-03 13:28
 * @Description: Token
 * @Version: 1.0
 */
public class TokenInterceptor implements HandlerInterceptor {

    /**
     * 前置拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * return true:放行
         * false：拦截
         */
        System.out.println("进拦截器了==========");
        //获取请求头  token为空
         String token = request.getHeader("User-Token");
        if (token == null || token.isEmpty()) {
            ResponseDto dto = new ResponseDto(6, "请携带token", null);
            response.setContentType("text/html;charset=utf8");
            response.getWriter().write(JSON.toJSONString(dto));
            return false;
        }
        //2.token过期
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            ResponseDto dto = new ResponseDto(6, "token过期,请先登录！", null);
            response.setContentType("text/html;charset=utf8");
            response.getWriter().write(JSON.toJSONString(dto));
            return false;
        }
        return true;
    }
}

